<template>
  <el-select
    filterable
    class="w100"
    v-model="selectList"
    multiple
    clearable
    placeholder="请选择"
    @change="e => changeSelect(e)"
  >
    <div class="checkboxWrapper">
      <el-checkbox v-model="checked" @change.native="checkChange">
        全选
      </el-checkbox>
    </div>
    <el-option
      v-for="(item,index) in options"
      :key="index"
      :label="item[props.label]"
      :value="item[props.value]"
    >
    </el-option>
  </el-select>
</template>

<script>
export default {
  model: {
    prop: "value",
    event: "change",
  },
  props:{
    options:{
      type:Array,
      default : ()=>{
        return []
      }
    },
    props: Object,
    data: {
      type:Array,
      default : ()=>{
        return []
      }
    }
  },
  data() {
    return {
      checked: false,
      selectList: [],
    };
  },
  created() {
    this.selectList = this.data || [];
    this.changeSelect(this.selectList) //回显
  },
  mounted() {
    console.log("this.options:",this.options)
  },
  methods: {
    checkChange() {
      let resValues = this.options.map(item => item[this.props.value]);
      // 如果checkbox为false，则为反选，选择数组为空
      if (!this.checked) {
        this.selectList = [];
      } else {
        // 如果checkbox为true，则为全选，选择数组添加所有数据
        let res = [...resValues];
        this.selectList = res;
      }
      this.$emit('change',this.selectList) ;
      this.$forceUpdate() ;
    },
    changeSelect(val) {
      let resValues = this.options.map(item => item[this.props.value]);
      // 如果选择数组长度等于options的长度，checkbox设为true，反之设为false
      if (val.length === resValues.length) {
        this.checked = true;
      } else {
        this.checked = false;
      }
      this.selectList = val;
      this.$emit('change',this.selectList) ;
    }
  }
};
</script>
<style scoped>
.checkboxWrapper {
  padding: 8px 20px;
  border-bottom: 1px solid #ccc;
}
</style>
